<template>
  <view class="identity need_scroll_top_view">
    <view class="h20"></view>
    <view class="top">身份证</view>
    <view class="cont">
      <view class="up-box" :class="{border: !imageFront}" @click="updateFile('front')">
        <block v-if="!imageFront">
          <image :src="$store.state.imgBaseUrl + '/id.png'" class="none"></image>
          <view>上传身份证正面</view>
        </block>
        <image :src="imageFront" class="boradius" v-else></image>
      </view>
      <view class="up-box" :class="{border: !imageVerso}" @click="updateFile('verso')" v-if="imageFront">
        <block v-if="!imageVerso">
          <image :src="$store.state.imgBaseUrl + '/id.png'" class="none" ></image>
          <view>上传身份证反面</view>
        </block>
        <image :src="imageVerso" class="boradius" v-else></image>
      </view>
    </view>
    <view class="text1">
      注：拍摄时请确保证件<text class="line">边框完整，字体清晰，亮度均匀</text>
    </view>
    <block v-if="imageFront || imageVerso">  
      <text class="text2">请确认您的个人信息，若有误请点击修改</text>
      <view class="row">
        <text class="tit">姓名</text>
        <text class="text3">
          <input type="text" v-model="info.name" @blur="backFixationTop()">
        </text>
      </view>
      <view class="row">
        <text class="tit">身份证</text>
        <text class="text3">
          <input type="text" v-model="info.id" @blur="backFixationTop()">
        </text>
      </view>
    </block>
    <view class="footer">
      <button type="primary" class="sub-btn cur" plain="true" @click="gotoPage">确认保存</button>
    </view>
    <view>
      <uni-fab
        :pattern="pattern"
        :content="content"
        :horizontal="horizontal"
        :direction="direction"
        @trigger="trigger"
      ></uni-fab>
    </view>
  </view>
</template>
<script>
import {uploadFile} from "@/unit/common.js"
import { discernCard, getModify } from "@/service/join/join.service.js"
import formValid from '@/unit/graceChecker.js'
import {getJoinStatus} from './common.js' // 获取审核结果的接口
import { scrollToTargetPosition } from '@/mixin/index.mixin.js'
import uniFab from '@/components/uni-fab/uni-fab.vue';
import { logoutApi } from '@/service/user/user.service.js'
export default {
  components: {uniFab},
  mixins: [scrollToTargetPosition],
  data() {
    return {
      getUserComposeInfo: null, // 获取被驳回存储的信息
      getUserJoinInfo: null, // 获取存储的信息
      isFrontUpdate: false, // 记录正面身份证是否正确
      recomposeInfo: null ,// 存储被驳回的加盟信息
      idCardImage1: null,
      idCardImage2: null,
      imageFront: null, //身份正面
      imageVerso: null, // 身份反面
      isBack: false ,// 记录背面身份证信息是否正确
      grade: null,
      type: null, // 加盟类型
      isId: 0,
      info: { // 身份信息
        name: '',
        id: ''
      },
      horizontal: 'right',
      direction: 'horizontal',
      pattern: {
        color: '#FFFFFF',
        backgroundColor: 'rgba(0,0,0,0.5)',
        selectedColor: '#007AFF',
        buttonColor:"#434343"
      },
      content: [
        {
          iconPath: '../../static/image/icon/loginout.png', // 图片路径
          text: '安全退出',
          active: false
        }
      ]
    };
  },
  onLoad:function(option){
    this.type = option.type;
  },
  mounted() {
    this.initDraw()
  },
  activated () {
    this.initDraw()
  },
  methods: {
    trigger(e) {
      if (e.index == 0) { // 购物车
        logoutApi({}, res => {
          if (res.status == 0) {
            uni.showToast({
              title: '登出成功！',
              success: () => {
                setTimeout(function () {
                  uni.clearStorageSync();
                 
                }, 2000);
              }
            })
          }
        }, null, {showErrorMsg: true});
      }
    },
    initDraw () {
      this.getUserJoinInfo = uni.getStorageSync('joinInfo');
      this.getUserComposeInfo = uni.getStorageSync('recomposeDatas');
      if (this.getUserComposeInfo) {
        this.recomposeInfo = this.getUserComposeInfo;
        this.isId = 1;
        this.imageFront = this.getUserComposeInfo.idCardImage1.url;
        this.imageVerso = this.getUserComposeInfo.idCardImage2.url;
        this.idCardImage1 = this.getUserComposeInfo.idCardImage1.id;
        this.idCardImage2 = this.getUserComposeInfo.idCardImage2.id;
        this.info.name = this.getUserComposeInfo.realname;
        this.info.id = this.getUserComposeInfo.idCardNumber;
        this.grade = this.getUserComposeInfo.rank; // 当前用户申请的等级
        this.isFrontUpdate = true;
        this.isBack = true // 记录背面身份证信息是否正确
      }
      if (!this.getUserJoinInfo && !this.getUserComposeInfo) {
        getJoinStatus((data)=>{ // 校验是否申请过加盟
          if (data == 'null' || data == 2 || data == 3) {
            uni.showToast({
              title: '请先选择加盟类型',
              icon: 'none',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/pages/join/index'
                  })
                }, 2000);
              }
            });
            return false;
          } else if (data != 1) {
            uni.showToast({
              title: '已提交申请',
              icon: 'none',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/pages/join/result'
                  })
                }, 2000);
              }
            });
            return false
          }
        });
      }
    },
    updateFile (type) {
      uploadFile({success: (obj) => {
        if(obj.status ==0) {
          if (type == 'front') {
            this.getInfo(0, obj.data.url, obj.data.id) // 0=>正面
          } else {
            this.getInfo(1, obj.data.url, obj.data.id) // 1=>反面
          }
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }})
    },
    getInfo (type, url, id) {
      uni.showLoading({
        title: '识别中',
        mask: true
      })
      let params = {
        id: id,
        appliedType: 2,
        isFace: type,
        url: url
      }
      discernCard(params, (res) => {
        if (res.status == 0) {
          this.isId = 1;
          if (type == 0) {
            this.isFrontUpdate = true;
            this.info.name = res.data.name;
            this.info.id = res.data.num;
            this.idCardImage1 = id;
            this.imageFront = url;
          } else {
            this.isBack = true;
            this.imageVerso = url;
            this.idCardImage2 = id;
          }
          uni.hideLoading()
        } else {
          if (type == 0) {
            this.idCardImage1 = '';
            this.imageFront = '';
            this.isFrontUpdate = false;
            this.info.name = '';
            this.info.id = '';
          } else {
            this.imageVerso = '';
            this.idCardImage2 = '';
            this.isBack = false;
          }
          this.isId = 0;
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
          uni.hideLoading()
        }
      })
    },
    gotoPage () {
      let rule = [
        {name:'name', checkType: 'notnull', checkRule:'', errorMsg:'请完善身份信息'},
        {name:'id', checkType: 'notnull', checkRule:'', errorMsg:'请完善身份信息'}
      ];
      var checkRes = formValid.check(this.info, rule);
      if (checkRes) {
        if (this.isFrontUpdate && this.isBack) {
          let params = {
            realname: this.info.name,
            idCardNumber: this.info.id,
            idCardImage1: this.idCardImage1,
            idCardImage2: this.idCardImage2
          }
          this.grade ? params['rank'] = this.grade : ''; // 存储等级
          if (!this.recomposeInfo) { // 申请加盟
            this.firstJoin(params);
          } else { // 被驳回
            this.recomposeJoinInfo(params);
          }
        } else {
          uni.showToast({ title: '请上传正确的身份证图片', icon: "none" });
        }
      } else {
        uni.showToast({ title: formValid.error, icon: "none" });
      }
    },
    firstJoin (params) { // 申请加盟
      uni.setStorage({
        key: 'joinInfo',
        data: {...params, ...this.getUserJoinInfo},
        success: () => {
          uni.navigateTo({
            url: '/pages/join/joinEntrance?type=' + this.type + '&isId=' + this.isId
          })
        }
      })
    },
    recomposeJoinInfo (params) {
      //joinStatus 4：资质驳回  6：资质财务均驳回
      if (this.recomposeInfo.joinStatus == 4) {
        if (this.type == 'person') { //个人申请加盟
          this.recomposeJoin(params); // 提交加盟信息
        } else { // 企业申请加盟
          //重置修改的内容并将其返回
          this.recomposeInfo.realname = params.realname;
          this.recomposeInfo.idCardNumber = params.idCardNumber;
          this.recomposeInfo.idCardImage1 = {id: params.idCardImage1, url: this.imageFront};
          this.recomposeInfo.idCardImage2 = {id: params.idCardImage2, url: this.imageVerso};
          uni.setStorage({
            key: 'recomposeDatas',
            data: this.recomposeInfo,
            success: () => {
              uni.navigateTo({
                url: '/pages/join/updateLicense?type=' + this.type
              })
            }
          })
        }
      } else if (this.recomposeInfo.joinStatus == 6) {
        this.recomposeInfo.realname = params.realname;
        this.recomposeInfo.idCardNumber = params.idCardNumber;
        this.recomposeInfo.idCardImage1 = {id: params.idCardImage1, url: this.imageFront};
        this.recomposeInfo.idCardImage2 = {id: params.idCardImage2, url: this.imageVerso};
        let url;
        if (this.type == 'person') {
          url = '/pages/join/updateCertificate?type=' + this.type
        } else {
          url = '/pages/join/updateLicense?type=' + this.type
        }
        uni.setStorage({
          key: 'recomposeDatas',
          data: this.recomposeInfo,
          success: () => {
            uni.navigateTo({
              url: url
            })
          }
        })
      }
    },
    recomposeJoin (params) {
      params['id'] = this.recomposeInfo.joinId;
      params['joinType'] = this.type == 'person' ? 1 : 0;
      params['onlinePay'] = 0;
      getModify(params, (res) => {
        if (res.status == 0) {
          uni.showToast({
            title: '提交成功',
            icon: 'none'
          });
          uni.removeStorageSync('recomposeDatas')
          uni.navigateTo({ // 审核页
            url: '/pages/join/result'
          })
          this.$store.dispatch('getUserInfo');
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
image {
  width: 100%;
  height: 100%;
}
.h20 {
  height: 20rpx;
}
.identity {
  height: 100vh;
  background-color: #FFFFFF;
  padding: 0 30rpx;
  color: #333333;
  .top {
    font-size: 36rpx;
    color: #333333;
    text-indent: 2rpx;
    padding-top: 42rpx;
  }
  .cont {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    .up-box {
      width: 330rpx;
      height: 200rpx;
      color: #666666;
      font-size: 24rpx;
      text-align: center;
      border-radius: 16rpx;
      .none {
        width: 79rpx;
        height: 79rpx;
        display: block;
        margin: 35rpx auto 29rpx;
      }
      &:first-of-type {
        margin-right: 27rpx;
      }
      .boradius {
        border-radius: 16rpx;
      }
      &.border {
        border: 1px dashed #E1E1E1;
      }
    }
  }
  .text1 {
    font-size: 22rpx;
    margin-top: 33rpx;
    text-align: center;
    .line {
      color: #C2AC78;
    }
  }
  .text2 {
    display: block;
    font-size: 22rpx;
    color: #666666;
    margin-top: 42rpx;
  }
  .row{
  	display: flex;
  	align-items: center;
  	padding: 30rpx 0;
    border-bottom: 1px solid #E1E1E1;
    font-size: 28rpx;
  	.tit{
  		flex-shrink: 0;
  		width: 120rpx;
      margin-right: 30rpx;
  	}
  	.text3{
  		flex: 1;
      color: #333333;
      input {
        font-size: 28rpx;
      }
  	}
  }
  .footer {
    width: 100%;
    border-top: 1px solid #E1E1E1;
    padding: 14rpx 0 20rpx;
    background-color: #FFFFFF;
    position: absolute;
    bottom: 0;
    left: 0;
    button {
      height: 70rpx;
      margin: 0 32rpx;
      background-color: #636363;
      line-height: 70rpx;
      font-size: 30rpx;
      color: #ADA697;
      border: none;
      &.cur {
        color: #F6DA99;
        background-color: #434343;
      }
    }
  }
}
</style>
